<template>
  <div>
    <a-form-model
      class="mt-6"
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      v-bind="{
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      }"
    >
      <a-form-model-item label="原始密码" prop="pass_old">
        <a-input
          v-model.trim="ruleForm.pass_old"
          type="password"
          autocomplete="off"
        />
      </a-form-model-item>
      <a-form-model-item label="新密码" prop="pass">
        <a-input
          v-model.trim="ruleForm.pass"
          type="password"
          autocomplete="off"
        />
      </a-form-model-item>
      <a-form-model-item label="确认新密码" prop="checkPass">
        <a-input
          v-model.trim="ruleForm.checkPass"
          type="password"
          autocomplete="off"
        />
      </a-form-model-item>

      <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
        <a-button type="primary" @click="submitForm('ruleForm')">
          提交
        </a-button>
        <a-button style="margin-left: 10px" @click="resetForm('ruleForm')">
          取消
        </a-button>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>
<script>
export default {
  data() {
    let checkPending
    let checkAge = (rule, value, callback) => {
      clearTimeout(checkPending)
      if (!value) {
        return callback(new Error('Please input '))
      }
      callback()
    }
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please input '))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please input '))
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入新密码不一致'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        pass_old: '',
        pass: '',
        checkPass: '',
      },
      rules: {
        pass: [{ validator: validatePass, trigger: 'change' }],
        checkPass: [{ validator: validatePass2, trigger: 'change' }],
        pass_old: [{ validator: checkAge, trigger: 'change' }],
      },
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.axios
            .put('/password/reset', {
              password_old: this.ruleForm.pass_old,
              password: this.ruleForm.pass,
              password_confirmation: this.ruleForm.checkPass,
            })
            .then((res) => {
              this.$message.success('修改密码成功')
              this.$router.push('/login')
            })
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
  },
}
</script>
